const router = require('koa-router')()
const MsgHelp =require('../database/msgs/msgHelp')
const VerifyUtils=require('../utils/VerifyUtils')
const UnReadMsgHelp =require('../database/unread/UnReadMsgHelp')


//保存消息
router.post('/api/saveMsg',async(ctx,next)=>{
    let msg=ctx.request.body

    let data= await MsgHelp.saveMsg(msg)
    ctx.body={
        code:0,
        data:data
    }
})



//获取聊天室消息,单聊
router.get('/api/getMsg',async(ctx,next)=>{
    let to_uid=ctx.request.query.to_uid-0
    let from_uid=ctx.request.query.from_uid-0
    VerifyUtils.tips(ctx,{to_uid},{from_uid})

    let start=ctx.request.query.start
    let limit=ctx.request.query.limit

    let data=[]
    if(start&&limit){
        data=await MsgHelp.getMsgListReverse(to_uid,from_uid,start,limit)
    }
    else{
        data= await MsgHelp.getMsgListReverse(to_uid,from_uid)
    }

    ctx.body={
        code:0,
        data:data
    }
})



//获取聊天室消息,群聊
router.get('/api/getGroupMsg',async(ctx,next)=>{

    let gid=ctx.request.query.gid
    let from_uid=ctx.request.query.from_uid
    let start=ctx.request.query.start
    let limit=ctx.request.query.limit
    VerifyUtils.tips(ctx,{gid},{from_uid})

    let data= await MsgHelp.getGroupMsgList(gid,from_uid,start,limit)

    ctx.body={
        code:0,
        data:data
    }
})





//获取消息列表消息
router.post('/api/getMyMsgList',async(ctx,next)=>{
    let to_uid=ctx.request.body.uid-0
    VerifyUtils.tips(ctx,{to_uid})

    let data= await MsgHelp.pushLastMsg(to_uid)
    ctx.body={
        code:0,
        data:data
    }
})



//删除消息
router.post("/api/removeMsg",async(ctx,next)=>{
    let mid=ctx.request.body.mid-0
    VerifyUtils.tips(ctx,{mid})

    await MsgHelp.removeMsg(mid)
    ctx.body={
        code:0,
        data:''
    }
})



//消息单聊读取
router.get('/api/readMsg',async(ctx,next)=>{
    let uid=ctx.request.query.uid-0
    let myuid=ctx.request.query.myuid-0
    VerifyUtils.tips(ctx,{uid},{myuid})

    let data= await MsgHelp.readMsg(uid,myuid)
    ctx.body={
        code:0,
        data:data
    }
})



//读取群聊消息
router.get('/api/readGroupMsg',async(ctx,next)=>{
    let gid=ctx.request.query.gid-0
    let myuid=ctx.request.query.myuid-0
    VerifyUtils.tips(ctx,{gid},{myuid})

    let data= await MsgHelp.readGroupMsg(gid,myuid)
    ctx.body={
        code:0,
        data:data
    }
})



//获取某个人的未读消息
router.get('/api/unreadMsg',async (ctx, next) => {
    let {to_uid}=ctx.request.query
    let data=await UnReadMsgHelp.getUnReadMsg(to_uid)
    if(!data){
        data={
            unRead:0,
            to_uid:to_uid-0,
            msg_ids:{}
        }
    }
    ctx.body={
        code:0,
        data:data
    }

})



//获取通知
router.get('/api/getNotice',async(ctx,next)=>{
    let myuid=ctx.request.query.myuid-0
    VerifyUtils.tips(ctx,{myuid})

    let data= await MsgHelp.readMsg(myuid)
    ctx.body={
        code:0,
        data:data
    }
})





module.exports = router
